﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MetricGR.Interpolation.Components
{
    public static class Common
    {
        public static string FieldInterpolationProperty = "InterpolationTemplateString";

        public static int FieldsWithInterpolationStringProperty(SPList list)
        {
            int counter = 0;
            foreach (SPField field in list.Fields)
            {
                string property = field.GetProperty(Common.FieldInterpolationProperty);
                if (!string.IsNullOrEmpty(property))
                {
                    counter++;
                }
            }
            return counter;
        }

        public static void RemoveEventRecieverFromList(SPList list, string eventReceiversClass)
        {
            for (int i = list.EventReceivers.Count - 1; i <= 0; i--)
            {
                if (i < 0) break;
                if (list.EventReceivers[i].Class.Equals(eventReceiversClass))
                {
                    try
                    {
                        list.EventReceivers[i].Delete();
                    }
                    catch { }
                }
            }
        }

        private static object _lock = new object();
        public static void AddEventReceiver(SPList list, string eventReceiversClass)
        {
            Common.RemoveEventRecieverFromList(list, typeof(InterpolationIER).ToString());

            // only add the event receiver if there is a field with the interpolation property in it.
            int fieldCount = Common.FieldsWithInterpolationStringProperty(list);
            if (fieldCount > 0)
            {
                lock (_lock)
                {
                    if (!Common.ListContainsEventReceiver(list, eventReceiversClass))
                    {
                        list.EventReceivers.Add(SPEventReceiverType.ItemUpdated, Assembly.GetExecutingAssembly().FullName, eventReceiversClass);
                    }
                }
            }
        }

        public static bool ListContainsEventReceiver(SPList list, string eventReceiversClass)
        {
            bool found = false;

            foreach (SPEventReceiverDefinition er in list.EventReceivers)
            {
                if (er.Class.Equals(eventReceiversClass))
                {
                    found = true;
                    break;
                }
            }

            return found;
        }
    }
}
